// packageA/pages/equipmentEnterList/equipmentEnterList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //入库类型
    valType: -1,
    //入库类型选项
    optionsType: [],
    //状态
    valState:-1,
    //状态选项
    optionsState:[{
      value: -1,
      text: "入库单状态",
    },{
      value: 1,
      text: "已完成",
    },{
      value: 2,
      text: "待入库",
    }],
    //搜索关键词
    searchValue:'',
    //开始时间
    startTime: '开始时间',
    //开始时间选择框
    showStartTime:false,
    //结束时间
    endTime: '结束时间',
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),
    //最小时间
    minDate2:null,
    //最大时间
    maxDate1: new Date().getTime(),
    maxDate2: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } 
      return value
    },
    //仓库
    depot:{
      id:null,
      name:'仓库'
    },
    //仓库选择框
    showDepot:false,
    //仓库选择数据
    depotList:[],
    //搜索仓库
    valueSearchDepot:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取入库类型字典
    this.getTypeList();  

    //获取列表数据
    this.getList();

    this.setData({
      authority:app.globalData.authority
    })
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
      type: 1,
      selectFields: ["id","orderNo", "splitRecordData", 'type', 'createDate', 'state', 'operator','returnOrderNo', 'relationOrderNo', 'inStorageType', 'remark','destination','depot','service','handler','prepared','inputDateTime','keepAccounts','checking','orderObj'],
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    } 

    //搜索单号
    if(this.data.searchValue){
      dataObj.orderNo='%' +this.data.searchValue+ '%';
    }

    //入库类型
    if(this.data.valType!=-1){
      dataObj['inStorageType.id']=this.data.valType;
    }

    //仓库
    if(this.data.depot.id){
      dataObj['depot.id']=this.data.depot.id;
    }

    //状态
    if(this.data.valState!=-1){
      dataObj.state=this.data.valState;
    }

    //入库日期
    if(this.data.startTime!='开始时间' && this.data.endTime!='结束时间'){
      dataObj.inputDateTime={
        '>=': this.data.startTime +' 00:00:00',
        '<=': this.data.endTime +' 23:59:59'
      }
    }
    
    let param = {
      isAuth: true,
      className: 'inStorageOrder',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          //入库时间
          if (item.inputDateTime){
            item.inputDateTime=util.timeFormat(item.inputDateTime);
          }

          //状态
          switch(item.state){
            case 1:
              item.stateWord='已完成';
              item.stateClass='c-1';
              break;
            case 2:
              item.stateWord='待入库';
              item.stateClass='c-2';
              break;
          }     
        });

        console.log('设备入库列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //获取入库类型字典
  getTypeList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'inStorageType',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[{
          value: -1,
          text: "入库类型"
        }];
        result.forEach(item => {
          arr.push({
            value:item.id,
            text:item.name
          });
        });
        this.setData({
          optionsType: arr
        })
      }
    }).catch((error) => {
    })
  },

  //入库类型筛选
  onChangeType({detail}){
    this.setData({ 
      valType: detail
    }) 
    this.refreshListAndPage();
  },

  //状态筛选
  onChangeState({detail}){
    this.setData({ 
      valState: detail
    }) 
    this.refreshListAndPage();
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //查看
  goToLook(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id,
      mark: 'detail'
    }
    wx.navigateTo({
      url: "/packageA/pages/equipmentEnter/equipmentEnter?paramObj="+JSON.stringify(obj)
    })
  },

  //入库
  goToEnter(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id,
      mark: 'enter'
    }
    wx.navigateTo({
      url: "/packageA/pages/equipmentEnter/equipmentEnter?paramObj="+JSON.stringify(obj)
    })
  },

  //作废
  onVoid(e){
    Dialog.confirm({
      title: '确定要作废当前入库单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不作废了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail; 

      let param={
        orderNo: detail.orderNo
      }

      CommonService.deleteInStorage(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已作废');
          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  //显示开始时间
  onShowStartTime(){
    this.setData({
			showStartTime: true
    })
  },

  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
			showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    this.setData({
      currentStart: e.detail,
      minDate2:e.detail,
      startTime:util.timeFormatDay(e.detail),
    })
    this.onCloseStartTime();

    if(this.data.endTime!='结束时间'){
      this.refreshListAndPage();
    }  
  },

  //显示结束时间
  onShowEndTime(){
    this.setData({
			showEndTime: true
    })
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
			showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    this.setData({
      currentEnd: e.detail,
      maxDate1:e.detail,
      endTime:util.timeFormatDay(e.detail),
    })
    this.onCloseEndTime();

    if(this.data.startTime!='开始时间'){
      this.refreshListAndPage();
    }
  },

  //清除时间
  onCancelTime(){
    this.setData({
      startTime: '开始时间',
      endTime: '结束时间'
    })
    
    this.onCloseStartTime();
    this.onCloseEndTime();
    this.refreshListAndPage();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //显示仓库
  onShowDepot(){
    this.setData({
			showDepot: true
    })
    this.getDepotList();
  },

  //查询仓库
  getDepotList(){
    this.setData({
      depotList: []
    })

    let param = {
      isAuth: false,
      className: 'partsDepots',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    //模糊查询
    if(this.data.valueSearchDepot){
      param.data.name='%' + this.data.valueSearchDepot + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          depotList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏仓库
  onCloseDepot(){
    this.setData({
      showDepot: false,
      valueSearchDepot:''
    })  
    this.refreshListAndPage();
  },

  //确认仓库
  onConfirmDepot(e){ 
    let id='depot.id';
    let name='depot.name';
    this.setData({
      [id]:e.detail.value.id,
      [name]:e.detail.value.text
    })
    
    this.onCloseDepot();
  },

  //搜索仓库
  onChangeDepotVal(e){
    this.setData({
      valueSearchDepot: e.detail
    })
    this.getDepotList();
  },

  //清除仓库选择
  onCancelDepot(){
    let id='depot.id';
    let name='depot.name';
    this.setData({
      [id]:null,
      [name]:'仓库'
    })
    this.onCloseDepot();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})